package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.utils.ValidateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class ValidateHandler extends AbstractTransHandler {


    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {

        // 获取context中的相应字段
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        Long userId = createOrderContext.getUserId();
        Long addressId = createOrderContext.getAddressId();
        String tel = createOrderContext.getTel();
        String userName = createOrderContext.getUserName();
        String streetName = createOrderContext.getStreetName();
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();

        // 这些字段如果有一个为null或为空则抛出异常
        ValidateUtil.validate(userId, addressId, tel, userName, streetName, cartProductDtoList);

        // 手机号格式不正确，抛出异常
        if (!tel.matches("1[3-9]\\d{9}")) {
            // throw new ValidateException(SysRetCodeConstants.REQUEST_DATA_ERROR.getCode(), SysRetCodeConstants.REQUEST_DATA_ERROR.getMessage());
            throw new ValidateException(SysRetCodeConstants.REQUEST_DATA_ERROR.getCode(), "手机号格式不正确");
        }

        return true;
    }
}
